#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sstream>
#include "log.hpp"

class Util
{
public:
    static bool ReadFile(const std::string &path, std::string *fileContent)
    {
        // 获取文件大小
        struct stat st;
        int n = stat(path.c_str(), &st);
        if (n < 0)
        {
            return false;
        }
        int size = st.st_size;

        // 调整string空间
        fileContent->resize(size);

        // 读取数据到缓冲区中
        int fd = open(path.c_str(), O_RDONLY);
        if (fd < 0)
        {
            return false;
        }
        read(fd, (char *)fileContent->c_str(), size);

        logMessage(Info, "read file: %s done", path.c_str());

        close(fd);

        return true;
    }

    // 用于获取序列化信息的一行
    static std::string ReadLine(std::string &message, const std::string &SEP)
    {
        auto pos = message.find(SEP);
        if(pos == std::string::npos)
        {
            return "";
        }
        std::string s = message.substr(0, pos);
        message.erase(0, pos + SEP.size());
        return s;
    }

    // 分割请求行
    static bool ParseRequestLine(const std::string& line, std::string* method, std::string* url, std::string* httpVersion)
    {
        std::stringstream ss(line);
        ss >> *method >> *url >> *httpVersion;
        return true;
    }
};